package cn.com.easy.permission.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.com.easy.permission.dao.RoleDao;
import cn.com.easy.permission.dao.UserDao;
import cn.com.easy.permission.dao.UserRolesMappingDao;
import cn.com.easy.permission.model.RoleModel;
import cn.com.easy.permission.model.UserModel;
import cn.com.easy.permission.model.UserRolesMappingModel;
import cn.com.easy.permission.service.system.role.SystemRoleService;
import cn.com.easy.permission.service.system.urlreserve.anotion.UrlReserveAnotion;
import cn.com.easy.permission.web.dto.MessageDTO;
import cn.com.easy.permission.web.dto.PageRequestParamDTO;
import cn.com.easy.utils.PageUtils;
import cn.com.easy.utils.ResponseOutputUtils;
import cn.com.easy.utils.SecurityUtils;

/**
 * 成员管理
 * 
 * @author nibili 2015年12月8日
 * 
 */
@Controller
@RequestMapping("/manage/system/member")
public class SystemMemberController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(SystemMemberController.class);

	/** 角色dao */
	@Autowired
	private RoleDao roleDao;
	/** 成员表dao */
	@Autowired
	private UserDao userDao;
	/** 成员服务类 */
	@Autowired
	private SystemRoleService systemRoleService;
	/** 用户角色对应表dao */
	@Autowired
	private UserRolesMappingDao userRolesMappingDao;

	/**
	 * 成员管理首页
	 * 
	 * @return
	 * @author nibili 2015年12月8日
	 */
	@UrlReserveAnotion("成员管理首页")
	@RequestMapping("")
	public String index(HttpServletRequest request, HttpServletResponse response) {
		return "/system/system_member/system_member";
	}

	/**
	 * 获取所有成员
	 * 
	 * @param request
	 * @param response
	 * @param pageRequestParamDTO
	 * @param searchText
	 * @author nibili 2015年12月8日
	 */
	@UrlReserveAnotion("获取所有成员")
	@RequestMapping("/get/all")
	public void getAllMembers(HttpServletRequest request, HttpServletResponse response, PageRequestParamDTO pageRequestParamDTO, String searchText) {
		try {
			Page<UserModel> springDataPage;
			if (StringUtils.isNotBlank(searchText) == true) {
				springDataPage = userDao.findLikeLoginnameOrRealname(searchText, pageRequestParamDTO.buildSpringDataPageRequest());
			} else {
				springDataPage = userDao.findAll(pageRequestParamDTO.buildSpringDataPageRequest());
			}
			cn.com.easy.utils.Page<UserModel> page = PageUtils.getPage(springDataPage);
			// page.setTotalItems(1000);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, page));
		} catch (Exception ex) {
			logger.error("获取所有成员异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "获取所有成员异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 保存或更新成员
	 * 
	 * @param request
	 * @param response
	 * @param userModel
	 * @author nibili 2015年12月9日
	 */
	@UrlReserveAnotion("保存或更新成员")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public void saveOrUpdateMember(HttpServletRequest request, HttpServletResponse response, UserModel userModel) {
		try {
			if (userModel.getId() == null) {
				// 新增
				userModel.setPassword(SecurityUtils.SHA256Normal(SecurityUtils.SHA256Normal("123456")));
				userDao.save(userModel);
			} else {
				// 更新
				UserModel userModelTemp = userDao.findOne(userModel.getId());
				if (userModelTemp == null) {
					ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "提交成员信息失败，未找到用户！"));
					return;
				} else {
					userModelTemp.setTel(userModel.getTel());
					userModelTemp.setRealname(userModel.getRealname());
					userModelTemp.setEmail(userModel.getEmail());
					userModelTemp.setIsAdmin(userModel.getIsAdmin());
					userModelTemp.setStatus(userModel.getStatus());
					userModelTemp.setMark(userModel.getMark());
					userDao.save(userModelTemp);
				}
			}
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, ""));
		} catch (Exception ex) {
			logger.error("提交成员信息异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "提交成员信息异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 删除成员
	 * 
	 * @param request
	 * @param response
	 * @param id
	 * @author nibili 2015年12月9日
	 */
	@UrlReserveAnotion("删除成员")
	@RequestMapping(value = "/delete")
	public void deleteMember(HttpServletRequest request, HttpServletResponse response, Long id) {
		try {
			userDao.delete(id);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, ""));
		} catch (Exception ex) {
			logger.error("删除成员异常，id:" + id, ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "删除成员异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 重置密码(系统默认密码为:123456)
	 * 
	 * @param request
	 * @param response
	 * @param id
	 *            用户id
	 * @author nibili 2015年12月9日
	 */
	@UrlReserveAnotion("重置密码")
	@RequestMapping(value = "/reset/password")
	public void resetPassword(HttpServletRequest request, HttpServletResponse response, Long id) {
		try {
			UserModel userModel = userDao.findOne(id);
			if (userModel != null) {
				userModel.setPassword(SecurityUtils.SHA256(SecurityUtils.SHA256("123456")));
				userDao.save(userModel);
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, ""));
			} else {
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "未找到用户"));
			}
		} catch (Exception ex) {
			logger.error("删除成员异常，id:" + id, ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "删除成员异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 获取成员所属角色
	 * 
	 * @param request
	 * @param response
	 * @param pageRequestParamDTO
	 * @author nibili 2015年12月8日
	 */
	@UrlReserveAnotion("获取成员所属角色 ")
	@RequestMapping("/get/roles")
	public void getRoles(HttpServletRequest request, HttpServletResponse response, PageRequestParamDTO pageRequestParamDTO, Long userId) {
		try {
			Page<RoleModel> roleModelsPage = userRolesMappingDao.findRolesByUserId(userId, pageRequestParamDTO.buildSpringDataPageRequest());
			cn.com.easy.utils.Page<RoleModel> page = PageUtils.getPage(roleModelsPage);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, page));
		} catch (Exception ex) {
			logger.error("获取成员所属角色异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "获取成员所属角色异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 获取所有角色
	 * 
	 * @param request
	 * @param response
	 * @param pageRequestParamDTO
	 * @author nibili 2015年12月8日
	 */
	@UrlReserveAnotion("获取所有角色")
	@RequestMapping("/get/roles/all")
	public void getAllRoles(HttpServletRequest request, HttpServletResponse response, PageRequestParamDTO pageRequestParamDTO) {
		try {
			Page<RoleModel> springDataPage = roleDao.findAll(pageRequestParamDTO.buildSpringDataPageRequest());
			cn.com.easy.utils.Page<RoleModel> page = PageUtils.getPage(springDataPage);
			// page.setTotalItems(1000);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, page));
		} catch (Exception ex) {
			logger.error("获取所有角色异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "获取所有角色异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 添加角色成员
	 * 
	 * @param request
	 * @param response
	 * @param roleId
	 * @param memberId
	 * @author linwk 2015年12月22日
	 */
	@UrlReserveAnotion("添加成员角色")
	@RequestMapping(value = "/add/role")
	public void addMember(HttpServletRequest request, HttpServletResponse response, Long roleId, Long memberId) {
		try {
			if (memberId == null || roleId == null) {
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "角色id 或者 成员id 为空！"));
				return;
			}
			UserModel userModelTemp = userDao.findOne(memberId);
			if (userModelTemp == null) {
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "成员信息查找失败，未找到该角色！"));
				return;
			} else {
				UserRolesMappingModel userRolesMappingModel = userRolesMappingDao.findByRoleIdAndUserId(roleId, memberId);
				if (userRolesMappingModel != null) {
					ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "角色已存在！"));
					return;
				}
				// 添加成员角色
				userRolesMappingModel = new UserRolesMappingModel();
				userRolesMappingModel.setCreateBy(this.getCurrentUser(request).getLoginname());
				userRolesMappingModel.setUserId(memberId);
				userRolesMappingModel.setRoleId(roleId);
				userRolesMappingDao.save(userRolesMappingModel);
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, ""));
			}
		} catch (Exception ex) {
			logger.error("添加成员角色异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "添加成员角色异常.ex:" + ex.getLocalizedMessage()));
		}

	}

	/**
	 * 删除成员角色
	 * 
	 * @param request
	 * @param response
	 * @param roleId
	 * @param memberId
	 * @author linwk 2015年12月22日
	 */
	@UrlReserveAnotion("删除成员角色")
	@RequestMapping(value = "/delete/role")
	public void deleteMember(HttpServletRequest request, HttpServletResponse response, Long roleId, Long memberId) {
		try {
			if (memberId == null || roleId == null) {
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "角色id 或者 成员id 为空！"));
				return;
			}
			UserModel userModelTemp = userDao.findOne(memberId);
			if (userModelTemp == null) {
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "成员信息查找失败，未找到该角色！"));
				return;
			} else {
				// 添加成员角色
				systemRoleService.deleteMember(roleId, memberId);
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, ""));
			}
		} catch (Exception ex) {
			logger.error("删除成员角色异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "成员角色异常.ex:" + ex.getLocalizedMessage()));
		}
	}
}
